package com.jeecms.wicool.action.product;

import static com.jeecms.common.page.SimplePage.cpn;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.common.web.ResponseUtils;
import com.jeecms.wicool.dao.product.ProductInnerRelationDao;
import com.jeecms.wicool.entity.image.ImageEntity;
import com.jeecms.wicool.entity.product.Product;
import com.jeecms.wicool.entity.product.ProductCate;
import com.jeecms.wicool.entity.product.ProductInnerRelation;
import com.jeecms.wicool.entity.product.ProductRelation;
import com.jeecms.wicool.entity.product.ProductSku;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.image.ImageEntityManager;
import com.jeecms.wicool.manager.product.ProductCateMng;
import com.jeecms.wicool.manager.product.ProductMng;
import com.jeecms.wicool.manager.product.ProductRelationMng;
import com.jeecms.wicool.manager.product.ProductSkuMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;

/**
 * 商品Action
 */
@Controller
public class ProductAct {
    private static final Logger log = LoggerFactory.getLogger(ProductAct.class);

    @SuppressWarnings("unchecked")
	@RequestMapping("/product/v_list.do")
    public String list(Integer productCateId, String productName, Integer pageNo, HttpServletRequest request, ModelMap model) {
        Pagination pagination = manager.getPage(productCateId, productName, cpn(pageNo),
                CookieUtils.getPageSize(request), CmsUtils.getUser(request));
        List<Product> listProduct = (List<Product>) pagination.getList();
        List<Dictionary2> listDic = DicMng.getList("product_status");
        List<Dictionary2> listDic2 = DicMng.getList("yes_or_no");
        Map<String, String> map = new HashMap<String, String>();
        Map<String, String> map2 = new HashMap<String, String>();
        for (Dictionary2 d : listDic) {
            map.put(d.getDicCode().toString(), d.getDicName());
        }
        for (Dictionary2 d : listDic2) {
            map2.put(d.getDicCode().toString(), d.getDicName());
        }
       for (Iterator<Product> iterator = listProduct.iterator(); iterator.hasNext();) {
			Product p = (Product) iterator.next();
			if("vip".equals(p.getUserLevel())){
				iterator.remove();
				continue;
	    	}
	        if (map.containsKey(p.getStatus().toString())) {
	            p.setStatusName(map.get(p.getStatus().toString()));
	        }
       }
        List<ProductCate> listProductCate = productCateMng.getListByCateLevel(null, CmsUtils.getUser(request));
        /*for (Iterator<ProductCate> iterator = listProductCate.iterator(); iterator.hasNext();) {
			ProductCate productCate = (ProductCate) iterator.next();
			if(productCate.getId() == 4){// 过滤掉VIP商品
				iterator.remove();
			}
		}*/
        model.addAttribute("pagination", pagination);
        model.addAttribute("productCateId", productCateId);
        model.addAttribute("productName", productName);
        model.addAttribute("listProductCate", listProductCate);

        return "product/list_product";
    }

    @RequestMapping("/product/a_list.do")
    public void list(Integer productCateId, HttpServletResponse response) {
        List<Product> products = manager.getAll(productCateId);
        List<JSONObject> temp = Lists.transform(products, new Function<Product, JSONObject>() {
            @Override
            public JSONObject apply(Product product) {
                JSONObject json = new JSONObject();
                json.put("id", product.getId());
                json.put("name", product.getProductName());
                return json;
            }
        });
        ResponseUtils.renderJson(response, JSONObject.toJSONString(temp));
    }

    @RequestMapping("/product/v_toEditProduct.do")
    public String toEditProduct(Integer id, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateEdit(id, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        model.addAttribute("product_id", id);
        return "product/to_edit_product";
    }

    @RequestMapping("/product/v_edit.do")
    public String edit(Integer id, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateEdit(id, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        Product product = manager.findById(id);
        List<ImageEntity> imageList = imageManager.getAll(id, ImageEntity.INDEX_SCROLL_IMG);
        product.setImgList(ImmutableSet.copyOf(imageList));
        List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
        List<ProductCate> listProductCate = productCateMng.getListByCateLevel(null, CmsUtils.getUser(request));
        /*for (Iterator<ProductCate> iterator = listProductCate.iterator(); iterator.hasNext();) {
			ProductCate productCate = (ProductCate) iterator.next();
			if(productCate.getId() == 4){// 过滤掉VIP商品
				iterator.remove();
			}
		}*/
        model.addAttribute("product", product);
        model.addAttribute("listShop", listShop);
        model.addAttribute("listProductCate", listProductCate);
        return "product/edit_product";
    }

    @RequestMapping("/product/v_edit_productRelation.do")
    public String editProductRelation(Integer productId, ProductRelation bean, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateEdit(productId, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        Product product = manager.findById(productId);
        ProductRelation productRelation = product.getProductRelation();
        if (productRelation == null) {
            productRelation = new ProductRelation();
        }
        productRelation.setProduct(product);
        if (bean.getId() != null) {
            model.addAttribute("productRelation", bean);
        } else {
            model.addAttribute("productRelation", productRelation);
        }
        return "product/edit_productRelation";
    }

    @RequestMapping("/product/v_edit_productSpecification.do")
    public String editProductSpecification(Integer productId, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateEdit(productId, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        List<ProductSku> specifications = productSkuMng.getListProductSku(productId);
        Product product = manager.findById(productId);
        model.put("specifications", specifications);
        model.put("product", product);

        return "product/edit_productSpecification";
    }

    @RequestMapping("/product/v_edit_productSku.do")
    public String editProductSku(Integer productId, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateEdit(productId, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        Product product = manager.findById(productId);
        List<ProductSku> listProductSku = productSkuMng.getListProductSku(productId);
        String skuCode;
        if (listProductSku != null && listProductSku.size() > 0) {
            List<Integer> listS = new ArrayList<Integer>();
            for (ProductSku ps : listProductSku) {
                ps.setProduct(product);
                listS.add(Integer.parseInt(ps.getSkuCode()));
            }
            skuCode = Collections.max(listS).toString();
        } else {
            skuCode = "0";
        }
        model.addAttribute("listProductSku", listProductSku);
        model.addAttribute("product", product);
        model.addAttribute("skuCode", skuCode);
        return "product/edit_productSku";
    }

    @RequestMapping("/product/o_save.do")
    public String save(Product bean, Integer shopId, Integer productCateId, String status, HttpServletRequest request, String[] imgUrls, Integer[] imgOrders, ModelMap model) {
        WebErrors errors = validateSave(bean, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        //获取系统当前登陆人
        CmsUser user = CmsUtils.getUser(request);
        bean.setPublisher(user.getId());
        //货号为空 自动生成
        if (bean.getItemNo() == null || bean.getItemNo().equals("")) {
            //获取当前数据库中最大货号值+1
            Integer maxItemNo = manager.getMaxItemNo();
            bean.setItemNo(Integer.toString((maxItemNo + 1)));
        }
        bean = manager.save(bean, shopId, productCateId);

        if (null != imgUrls) {
            List<ImageEntity> entities = Lists.newLinkedList();
            for (int i = 0; i < imgUrls.length; i++) {
                ImageEntity entity = new ImageEntity();
                entity.setImageURL(imgUrls[i]);
                entity.setRelationId(bean.getId());
                entity.setOrder(imgOrders[i]);
                entity.setImgType(ImageEntity.INDEX_SCROLL_IMG);
                entities.add(entity);
            }
            for (ImageEntity entity : entities) {
                imageManager.save(entity);
            }
        }
        if (!Strings.isNullOrEmpty(bean.getImgUrl())) {
            ImageEntity entity = new ImageEntity(null, bean.getId(), bean.getImgUrl(), 0, ImageEntity.SMALL_IMG);
            imageManager.save(entity);
        }

        log.info("save Product id={}", bean.getId());
        cmsLogMng.operating(request, "Product.log.save", "id=" + bean.getId());
        return "redirect:v_list.do";
    }

    @RequestMapping("/product/o_update.do")
    public String update(Product bean, Integer shopId, final Integer productCateId, String status, Integer pageNo, String[] imgUrls, Integer[] imgOrders, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateUpdate(bean.getId(), request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = simpleTime.format(new Date());
        Timestamp t = Timestamp.valueOf(dateTime);

        bean.setUpdateTime(t);

        //删除原有图片
        final Product product = manager.findById(bean.getId());
        List<ImageEntity> imgList = imageManager.getAll(bean.getId(), ImageEntity.INDEX_SCROLL_IMG);
        product.getImgList().clear();
        for (ImageEntity imageEntity : imgList) {
            imageManager.deleteById(imageEntity.getId());
        }
        List<ImageEntity> entities = Lists.newLinkedList();
        if (null != imgUrls) {
            for (int i = 0; i < imgUrls.length; i++) {
                ImageEntity entity = new ImageEntity();
                entity.setImageURL(imgUrls[i]);
                entity.setRelationId(product.getId());
                entity.setOrder(imgOrders[i]);
                entity.setImgType(ImageEntity.INDEX_SCROLL_IMG);
                entities.add(entity);
            }
            for (ImageEntity entity : entities) {
                imageManager.save(entity);
            }
        }
        bean = manager.update(bean, shopId, productCateId);
        bean.setImgList(Sets.newHashSet(entities));
        model.addAttribute("message", "global.success");
        log.info("update Product success. id={}", bean.getId());
        cmsLogMng.operating(request, "Product.log.update", "id=" + bean.getId());
        return edit(bean.getId(), request, model);
    }

    @RequestMapping("/product/o_updateProductRelation.do")
    public String updateProductRelation(ProductRelation bean, Integer productId, Integer pageNo, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateUpdateForProductRelation(bean.getId(), request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        Product product = manager.findById(productId);
        bean.setProduct(product);
        if (bean.getId() == null) {  //保存
            bean = productRelationMng.save(bean);
        } else { //更新
            SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateTime = simpleTime.format(new Date());
            Timestamp t = Timestamp.valueOf(dateTime);
            bean.setUpdateTime(t);
            bean = productRelationMng.update(bean);
        }
        model.addAttribute("message", "global.success");
        return editProductRelation(productId, bean, request, model);
    }

    @RequestMapping("/product/sku/a_list.do")
    public void getAllProductSku(Integer productId, HttpServletRequest request, HttpServletResponse response) {
        List<ProductSku> skuList = productSkuMng.getListProductSku(productId);
        List<JSONObject> pojos = Lists.transform(skuList, new Function<ProductSku, JSONObject>() {
            @Override
            public JSONObject apply(ProductSku sku) {
                JSONObject json = new JSONObject();
                json.put("skuName", sku.getSkuName());
                json.put("id", sku.getId());
                return json;
            }
        });
        ResponseUtils.renderJson(response, JSONObject.toJSONString(pojos));
    }

    @RequestMapping("/product/o_updateProductSku.do")
    public String updateProductSku(Integer productId, Integer[] psId, String[] skuCode, String[] skuName, BigDecimal[] price, BigDecimal[] priceMarket,
                                   Integer[] storeNum, BigDecimal[] freight
            , Integer pageNo, HttpServletRequest request, ModelMap model) {
//		WebErrors errors = validateUpdateForProductRelation(bean.getId(), request);
//		if (errors.hasErrors()) {
//			return errors.showErrorPage(model);
//		}
        Product product = manager.findById(productId);
        List<ProductSku> listProductSku = getListProductSku(product, psId, skuCode, skuName, price, priceMarket, storeNum, freight);
        productSkuMng.updateList(listProductSku, productId);
        model.addAttribute("message", "global.success");
        return editProductSku(productId, request, model);
    }

    public List<ProductSku> getListProductSku(Product product, Integer[] psId, String[] skuCode, String[] skuName, BigDecimal[] price, BigDecimal[] priceMarket,
                                              Integer[] storeNum, BigDecimal[] freight) {
        List<ProductSku> list = new ArrayList<ProductSku>();
        ProductSku ps;
        for (int i = 0; i < skuCode.length; i++) {
            ps = new ProductSku();
            if (psId != null && psId[i] != null) {
                ps.setId(psId[i]);
            }
            ps.setSkuCode(StringUtils.isEmpty(skuCode[i]) ? "" : skuCode[i]);
            ps.setSkuName(StringUtils.isEmpty(skuName[i]) ? "" : skuName[i]);
            ps.setPrice(price[i] == null ? BigDecimal.ZERO : price[i]);
            ps.setPriceMarket(priceMarket[i] == null ? BigDecimal.ZERO : priceMarket[i]);
            ps.setFreight(freight[i] == null ? BigDecimal.ZERO : freight[i]);
            ps.setStoreNum(storeNum[i]== null ? 0 : storeNum[i]);
            ps.setProduct(product);
            list.add(ps);
        }
        return list;
    }

    /**
     * 添加商品类型
     *
     * @param model
     * @return
     */
    @RequestMapping("/product/v_add.do")
    public String add(ModelMap model, HttpServletRequest request) {
        Product product = new Product();
        List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
        List<ProductCate> listProductCate = productCateMng.getListByCateLevel(null, CmsUtils.getUser(request));
       /* for (Iterator<ProductCate> iterator = listProductCate.iterator(); iterator.hasNext();) {
			ProductCate productCate = (ProductCate) iterator.next();
			if(productCate.getId() == 4){// 过滤掉VIP商品
				iterator.remove();
			}
		}*/
        List<Dictionary2> listDic = DicMng.getList("product_status");
        model.addAttribute("product", product);
        model.addAttribute("listShop", listShop);
        model.addAttribute("listProductCate", listProductCate);
        model.addAttribute("listDic", listDic);
        return "product/add_product";
    }

    @RequestMapping("/product/o_delete.do")
    public String delete(Integer[] ids, Integer productCateId, String productName, Integer pageNo, HttpServletRequest request,
                         ModelMap model) {
        WebErrors errors = validateDelete(ids, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        Product[] beans = manager.deleteByIds(ids);
        for (Product bean : beans) {
            log.info("delete Product id={}", bean.getId());
            cmsLogMng.operating(request, "Product.log.delete", "id="
                    + bean.getId() + ";name=" + bean.getProductName());
            List<ImageEntity> entities = imageManager.getAll(bean.getId(), ImageEntity.SMALL_IMG);
            for (ImageEntity entity : entities) {
                imageManager.deleteById(entity.getId());
            }
        }
        return list(productCateId, productName, pageNo, request, model);
    }

    @Autowired
    private ProductInnerRelationDao productInnerRelationDao;
    
    @RequestMapping("/product/v_setOption.do")
    public String to_setOption(Integer productId,ModelMap model, HttpServletRequest request) {
    	
    	List<ProductInnerRelation> list = productInnerRelationDao.getListProductInnerRelation(productId);
    	if(CollectionUtils.isEmpty(list)){
    		ProductInnerRelation withFood = new ProductInnerRelation();
    		withFood.setProductId(productId);
    		withFood.setType("withFood");
    		model.addAttribute("withFood", withFood);
    		
    		ProductInnerRelation soup = new ProductInnerRelation();
    		soup.setProductId(productId);
    		soup.setType("soup");
	        model.addAttribute("soup", soup);
    	}else{
    		for (ProductInnerRelation productInnerRelation : list) {
				if("withFood".equals(productInnerRelation.getType())){
					model.addAttribute("withFood", productInnerRelation);
				}else if("soup".equals(productInnerRelation.getType())){
					 model.addAttribute("soup", productInnerRelation);
				}
			}
    	}
       
        return "product/set_productOptions";
    }
    
    @RequestMapping("/product/o_updateProductOption.do")
    public String setOption(Integer[] id,Integer[] productId,String[] type,String[] value,ModelMap model, HttpServletRequest request) {
    	
    	manager.saveProductInnerRelation(id, productId, type, value);
       
        return "redirect:v_list.do";
    }
    
    private WebErrors validateSave(Product bean, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);
        return errors;
    }

    private WebErrors validateEdit(Integer id, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);
        if (vldExist(id, errors)) {
            return errors;
        }
        return errors;
    }

    private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);
        if (vldExist(id, errors)) {
            return errors;
        }
        // TODO 验证是否为管理员，管理员不允许修改。
        return errors;
    }

    private WebErrors validateUpdateForProductRelation(Integer id, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);
        if (vldExistForProductRelation(id, errors)) {
            return errors;
        }
        // TODO 验证是否为管理员，管理员不允许修改。
        return errors;
    }

    private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);
        errors.ifEmpty(ids, "ids");
        for (Integer id : ids) {
            vldExist(id, errors);
        }
        return errors;
    }

    private boolean vldExist(Integer id, WebErrors errors) {
        if (errors.ifNull(id, "id")) {
            return true;
        }
        Product entity = manager.findById(id);
        if (errors.ifNotExist(entity, Product.class, id)) {
            return true;
        }
        return false;
    }

    private boolean vldExistForProductRelation(Integer id, WebErrors errors) {
        if (errors.ifNull(id, "id")) {
            return true;
        }
        ProductRelation entity = productRelationMng.findById(id);
        if (errors.ifNotExist(entity, ProductRelation.class, id)) {
            return true;
        }
        return false;
    }

    @Autowired
    private ProductMng manager;
    @Autowired
    private ProductCateMng productCateMng;
    @Autowired
    private WiShopInfoMng shopMng;
    @Autowired
    private CmsLogMng cmsLogMng;
    @Autowired
    private DictionaryMng DicMng;
    @Autowired
    private ProductRelationMng productRelationMng;
    @Autowired
    private ProductSkuMng productSkuMng;

    @Autowired
    private ImageEntityManager imageManager;
}

